import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
// import 'package:euromillions/tools/EJ_ballsView.dart';
// import 'package:euromillions/tools/EJ_config.dart';
// import 'package:euromillions/tools/EJ_emsBalls.dart';
// import 'package:euromillions/tools/models/EJ_DataViewModels.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:intl/intl.dart';
// import 'package:kerala_lottery/tools/KaL_drawNumbersView.dart';
// import 'package:kerala_lottery/tools/models/KL_keralaLottoDataModel.dart';

import '../Results/KaL_resultDetailPage.dart';
import '../tools/KaL_Config.dart';
import '../tools/FL_CustomLoading.dart';
import '../tools/FL_emsBalls.dart';
import '../tools/KaL_drawNumbersView.dart';
import '../tools/models/KL_keralaLottoDataModel.dart';
import '../tools/models/KL_keralaLottoModel.dart';
import '../tools/models/KaL_DataViewModels.dart';
import '../tools/sqLite/EJ_myTicketEntity.dart';
import 'EJ_checkerDetailPageVC.dart';
import 'ScanTicket/KaL_scanTicketPage.dart';
// import '../tools/sqLite/EJ_myTicketEntity.dart';
// import 'EJ_checkerDetailPageVC.dart';

// ignore: must_be_immutable
class EJCHeckerPageVC extends StatefulWidget {
  EJCHeckerPageVC({super.key, this.pageController});
  PageController? pageController;

  @override
  State<EJCHeckerPageVC> createState() => _EJCHeckerPageVCState();
}

class _EJCHeckerPageVCState extends State<EJCHeckerPageVC>
    with SingleTickerProviderStateMixin {
  ///
  final ScrollController _scrollController = ScrollController();

  ///保存选号到数据库
  MyTicketEntity ticketEntity = MyTicketEntity.instan();

  //

  // late var _payouttables = []; //所有期的payouttable集合
  // late var _currentPayoutTable = []; //当前日期的payouttable
  //
  late List _drawDates = []; //所有日期集合
  late List _drawResultBalls = []; //所有期的ball集合
  late List _currentNumbers = []; //当前选中日期的balls
  int _currentDayIndex = 0; //选中日期的下标

  ///
  late var _resultList = [];
  late List _datas = []; //列表数据源
  var _expanded = false; //是否展开号码详情
  late List _checkerDatas = [];
  late List _prizes = [];
  PrizeModel _prizeModel = PrizeModel();

  ///
  _addTicket() {
    widget.pageController!.jumpToPage(2);
  }

  _reloadPage() {
    print('reloadPage');
  }

  _scanTicket() {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => KalScanticketpage(
          saveCallback: (callBackCode) {
            print('callBackCode-$callBackCode');
            if (callBackCode == 1) {
              _getAllTicket();
            }
          },
        ),
      ),
    );
  }

  ///
  _goToDetailPage(var numbers) {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => EJ_checkerDetailPageVC(
                  myTicketNumbers: numbers,
                )));
  }

  void _goToResultDetailPage(List prizes) {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => KalResultdetailpage(
                  prizes: prizes,
                )));
  }

  doNothing(BuildContext context, int index, var idString) {
    debugPrint('delete');
    _deleteTicketWith(index, idString);
  }

  //
  _getHeaderViewData() async {
    ///
    List checkerDatas = KL_keralaLottoDataModel().checkerDatas;
    _checkerDatas = checkerDatas.reversed.toList();
    for (Map element in _checkerDatas) {
      var dateStr = element['date'];
      DateTime date = DateTime.parse(dateStr + '+0000').toLocal();
      String dayOfWeek = DateFormat('EEE').format(date);
      String dayOfMonth = DateFormat('d').format(date);
      var dateString = {"weekDay": dayOfWeek, "day": dayOfMonth};
      // debugPrint('dateString---$dateString');
      _drawDates.add(dateString);
    }
    _currentDayIndex = _drawDates.length - 1;
    _prizeModel = _checkerDatas.last['prizes'][0];
    _prizes = _checkerDatas[_currentDayIndex]['prizes'];

    setState(() {});
  }

  _getResultBalls(var cNumbers) {
    _currentNumbers.clear();
    for (var i = 0; i < cNumbers.length; i++) {
      // if (i < cNumbers.length - 1) {
      if (i < KaL_Config.regularNumCount) {
        var element = cNumbers[i];
        var ball = {'number': element, 'isRegular': true};
        _currentNumbers.add(ball);
      } else {
        var element = cNumbers[i];
        var ball = {'number': element, 'isRegular': false};
        _currentNumbers.add(ball);
      }
    }
  }

  ///选中日
  _drawDateClick(int index) {
    BotToast.showCustomLoading(toastBuilder: (cancelFunc) {
      return FLCustomLoading();
    });
    _currentDayIndex = index;
    _prizeModel = _checkerDatas[index]['prizes'][0];
    _prizes = _checkerDatas[_currentDayIndex]['prizes'];

    Future.delayed(const Duration(milliseconds: 300), () {
      BotToast.closeAllLoading();
    });
    setState(() {});
  }

  //删除某个记录
  _deleteTicketWith(int index, var idString) {
    //删列表
    _datas.removeAt(index);

    ///删数据库
    ticketEntity.remove({"id": idString});

    setState(() {});
  }

  ///取出保存的ticket
  _getAllTicket() async {
    var result = await ticketEntity.find();
    // 处理查询结果
    // List<Map<String, dynamic>> resultList = result.toList();
    _resultList = result.toList();
    for (Map rowData in _resultList) {
      // 处理每行数据

      var idStr = rowData['id'];
      var name = rowData['name'];
      var numbers = jsonDecode(rowData['numbers']);
      debugPrint('rowData-$rowData');
      var ticket = {"id": idStr, "name": "$name", "numbers": numbers};
      _datas.add(ticket);
    }
    debugPrint('_datas---$_datas');
    setState(() {});
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _getHeaderViewData();
    _getAllTicket();

    ///
    Future.delayed(const Duration(milliseconds: 200), () {
      // _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
      _scrollController.animateTo(_scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 200), curve: Curves.ease);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // title: const Text(
        //   'Checker',
        //   style: TextStyle(
        //     fontWeight: FontWeight.w600,
        //     fontSize: 18,
        //   ),
        // ),
        title: Image.asset(
          'assets/sys_imgs/DearLottery Logo.png',
          width: 160,
          height: 50,
        ),
        backgroundColor: Colors.white,
        foregroundColor: KaL_Config.KaL_MainColor,
        centerTitle: true,
      ),
      body: Container(
        color: KaL_Config.KaL_pageBgColor,
        child: Column(
          children: [
            headerView(),
            bodyContentList(),
          ],
        ),
      ),
    );
  }

  Widget bodyContentList() {
    return Expanded(
        child: ListView.builder(
            // padding: const EdgeInsets.fromLTRB(15, 15, 15, 1),
            // itemCount: _datas.length + 2,
            itemCount: _datas.length + 2,
            itemBuilder: (BuildContext context, int index) {
              if (index == 0) {
                return ListHeaderText();
              } else if (index == (_datas.length + 2) - 1) {
                return ListFooterText();
              } else {
                int idx = index - 1;
                var data = _datas[idx];
                return cellSlidable(data, idx);
              }
            }));
  }

  Widget cellSlidable(Map data, int index) {
    var idStr = data['id'];
    return Padding(
      // key: ValueKey(index),
      padding: const EdgeInsets.only(top: 7.5, bottom: 7.5),
      child: Slidable(
        // controller: controller,
        // Specify a key if the Slidable is dismissible.
        // key: ValueKey(index),
        key: UniqueKey(),

        // The start action pane is the one at the left or the top side.
        startActionPane: ActionPane(
          // A motion is a widget used to control how the pane animates.
          motion: const ScrollMotion(),

          // A pane can dismiss the Slidable.
          dismissible: DismissiblePane(onDismissed: () {
            debugPrint('dismiss');
            _deleteTicketWith(index, idStr);
          }),

          // All actions are defined in the children parameter.
          children: [
            // A SlidableAction can have an icon and/or a label.
            SlidableAction(
              // onPressed: doNothing(context, index, idStr),
              onPressed: (BuildContext context) {
                doNothing(context, index, idStr);
              },
              backgroundColor: KaL_Config.KaL_themeColor_HL,
              foregroundColor: Colors.white,
              icon: Icons.delete,
              // padding: const EdgeInsets.only(left: 50, right: 50, bottom: 30),
              borderRadius: const BorderRadius.all(Radius.circular(12)),
              // backgroundColor: Colors.orange,
              // flex: 8,
              label: 'Delete',
            ),
            // SlidableAction(
            //   onPressed: (BuildContext context) {},
            //   label: "",
            //   backgroundColor: Colors.transparent,
            //   // flex: 1,
            // ),
            // SlidableAction(
            //   onPressed: doNothing,
            //   backgroundColor: Color(0xFF21B7CA),
            //   foregroundColor: Colors.white,
            //   icon: Icons.share,
            //   label: 'Share',
            // ),
          ],
        ),
        // child: contentListCell(data, index),
        child: listCell(data, index),
      ),
    );
  }

  bool compearMatchingElements(
      List<String> currentArray, List<String> subArray) {
    bool count = false;

    ///
    String cArr = currentArray.join('');
    String sArr = subArray.join('');
    if (right(cArr, sArr.length) == sArr) {
      count = true;
    }

    return count;
  }

  String right(String str, int length) {
    return str.substring(str.length - length);
  }

  Widget listCell(Map data, int index) {
    var _ticketName = data['name'];
    List numbers = data['numbers'];

    List<String> numbersList = [];
    // 将 List<dynamic> 转换为 List<String>
    // 将每个元素转换为字符串，如果是 null 则替换为空字符串
    numbersList = numbers.map((item) => item?.toString() ?? '').toList();

    var numbersMap = {};
    List<String> mostSimilar = [];
    bool bingo = false;

    var _pModel = PrizeModel();
    for (PrizeModel prizeModel in _prizes) {
      if (!bingo) {
        List? ticketNumbers = prizeModel.ticket_numbers;
        if (ticketNumbers != null) {
          for (var tNumbers in ticketNumbers) {
            List<String> tNumberList = tNumbers.split('');
            bingo = compearMatchingElements(numbersList, tNumberList);
            if (bingo) {
              mostSimilar = tNumberList;
              _pModel = prizeModel;
              break;
            }
          }
        }
      }
    }

    ///
    List nums = [];
    nums.clear();
    for (var i = numbers.length - 1; i >= 0; i--) {
      String cNum = numbers[i];
      bool isRight = false;
      if (mostSimilar.isNotEmpty) {
        int numbersLength = numbers.length;
        int mostSimilarLength = mostSimilar.length;
        int idx = i - (numbersLength - mostSimilarLength);
        if (idx >= 0) {
          String rNum = mostSimilar[idx];
          if (cNum == rNum) {
            isRight = true;
          }
        }
      }
      var num = {
        'number': cNum,
        'isRight': isRight,
        'isNormal': false
      }; //isNormal代表是否对比中奖号码，true不用对比，false需要对比。isRight代表是否中奖号码
      nums.add(num);
    }

    var prizeAmount = '';
    var prize = '';
    var title = 'No Matched Prizes';
    if (mostSimilar.isNotEmpty) {
      prize = _pModel.rank_title;
      prizeAmount = _pModel.prize_amount;
      prizeAmount = prizeAmount + ' INR';
      title = 'Matched $prize Prize';
    }
    numbersMap = {'title': title, 'balls': nums.reversed.toList()};

    return SizedBox(
      height: 140,
      child: GestureDetector(
        onTap: () {
          debugPrint('result');
          _goToDetailPage(nums.reversed.toList());
        },
        child: Container(
          margin: const EdgeInsets.fromLTRB(15, 0, 15, 1),
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10)),
          ),
          child: Column(children: [
            Container(
              margin: const EdgeInsets.only(left: 10, right: 10),
              height: 40,
              // color: Colors.yellow,
              child: Row(children: [
                Text(_ticketName,
                    style: const TextStyle(
                      fontWeight: FontWeight.w600,
                      fontSize: 13,
                      color: Colors.black,
                    )),
                const Spacer(),
                Text(
                  prizeAmount,
                  style: TextStyle(
                      fontWeight: FontWeight.w700,
                      fontSize: 15,
                      color: HexColor('#D32F7D')),
                ),
              ]),
            ),
            Expanded(
                child: Container(
              width: double.infinity,
              child: Row(
                children: [
                  Expanded(
                      child: Container(
                    // color: Colors.red,
                    alignment: Alignment.centerLeft,
                    child: KalDrawnumbersview(data: numbersMap),
                  )),
                  assetTagView(),
                ],
              ),
            )),
          ]),
        ),
      ),
    );
  }

  Widget assetTagView() {
    return Container(
      alignment: Alignment.center,
      height: double.infinity,
      width: 30,
      decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topRight: Radius.circular(10),
            bottomRight: Radius.circular(10),
          )),
      child: Image.asset(
        'assets/sys_imgs/EJ_union.png',
        width: 8.0,
        height: 13.0,
      ),
    );
  }

  //
  Widget ball(
    String num,
    bool isRegular, {
    bool isRightNumber = false,
    bool isMyTicket = false,
  } //是否是选中的号码
      ) {
    double viewW = 40.0;
    double margin = 5;
    double radius = (viewW - margin) * 0.5;
    Color bgColor = isRegular
        ? KaL_Config.KaL_themeColor_HL
        : KaL_Config.KaL_extramNumColor;
    Color textColor = Colors.white;
    Color borderColor = HexColor('#aaaaaa');
    //
    if (isMyTicket) {
      Color bgGrayColor = isRegular ? HexColor('#aaaaaa') : HexColor('666666');
      bgColor = isRightNumber ? bgColor : bgGrayColor;
      textColor = isRightNumber ? Colors.white : textColor;
      borderColor = isRightNumber ? KaL_Config.KaL_MainColor : borderColor;
    }

    // var extramNumImg = 'assets/systems_Imgs/extramNum_Star_gray.png';
    if (!isRegular && isRightNumber) {
      textColor = KaL_Config.KaL_extramNumTitleColor;
      borderColor = KaL_Config.KaL_extramNumBoardColor;
      // extramNumImg = 'assets/systems_Imgs/extramNum_Star.png';
      // viewW = 42.0;
      // radius = 0.0;
    }

    double padding = 0;
    //星星不需要圆角
    // if (!isRegular) {
    //   viewW = 42.0;
    //   radius = 0.0;
    //   padding = 3.0;
    // }

    return SizedBox(
      width: viewW,
      height: viewW,
      child: Container(
        alignment: Alignment.center,
        margin: EdgeInsets.all(margin),
        decoration: BoxDecoration(
          color: bgColor,
          // color: Colors.green,
          borderRadius: BorderRadius.all(Radius.circular(radius)),
          border: Border.all(width: 2, color: borderColor),
          // image: !isRegular
          //     ? DecorationImage(
          //         image: AssetImage(extramNumImg), // 替换为您的图片路径
          //         fit: BoxFit.cover, // 图片填充方式
          //       )
          //     : null,
        ),
        child: Padding(
          padding: EdgeInsets.only(top: padding),
          child: Text(
            num,
            style: TextStyle(
              color: textColor,
              fontWeight: FontWeight.w600,
              fontSize: 14,
            ),
          ),
        ),
      ),
    );
  }

  Widget headerView() {
    double btnH = 36.0;
    double btnW = 130.0;
    List<Widget> days = [];
    for (var i = 0; i < _drawDates.length; i++) {
      var date = _drawDates[i];
      days.add(DateView(date, i));
    }

    var numbersMap = {};
    List balls = [];
    List ticketNumbers = _prizeModel.ticket_numbers!;
    if (ticketNumbers.isNotEmpty) {
      String numberStr = ticketNumbers[0];
      // // 使用 split 方法将字符串转换为字符串数组
      List<String> charArray = numberStr.split('');
      // numbersMap = charArray;
      for (var i = 0; i < charArray.length; i++) {
        var ball = {
          'number': charArray[i],
          'isRight': false,
          'isNormal': true
        }; //isNormal代表是否对比中奖号码，true不用对比，false需要对比。isRight代表是否中奖号码
        balls.add(ball);
      }
      var title = _prizeModel.rank_title +
          ' Prize' +
          '-' +
          _prizeModel.prize_amount +
          ' INR';
      numbersMap = {'title': title, 'balls': balls};
    }

    return Column(
      children: [
        Container(
          height: 76,
          color: Colors.white,
          child: Row(
            children: [
              Expanded(
                child: Container(
                  // color: Colors.lightGreen,
                  alignment: Alignment.center,
                  child: Container(
                    height: btnH,
                    width: btnW,
                    decoration: BoxDecoration(
                        color: KaL_Config.KaL_MainColor,
                        borderRadius:
                            BorderRadius.all(Radius.circular(btnH * 0.5))),
                    child: TextButton(
                        onPressed: () {
                          debugPrint('Scan Ticket');
                          // _addTicket();
                          _scanTicket();
                        },
                        child: const Text(
                          'Scan Ticket',
                          style: TextStyle(
                            fontSize: 13,
                            fontWeight: FontWeight.w600,
                            color: Colors.white,
                          ),
                        )),
                  ),
                ),
              ),
              Expanded(
                child: Container(
                  alignment: Alignment.center,
                  child: Container(
                    height: btnH,
                    width: btnW,
                    decoration: BoxDecoration(
                        color: KaL_Config.KaL_MainColor,
                        borderRadius:
                            BorderRadius.all(Radius.circular(btnH * 0.5))),
                    child: TextButton(
                        onPressed: () {
                          debugPrint('Add Ticket');
                          _addTicket();
                        },
                        child: const Text(
                          'Add Ticket',
                          style: TextStyle(
                            fontSize: 13,
                            fontWeight: FontWeight.w600,
                            color: Colors.white,
                          ),
                        )),
                  ),
                ),
              ),
            ],
          ),
        ),
        Container(
          height: 74,
          width: double.infinity,
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Padding(
                padding: EdgeInsets.only(left: 20),
                child: Text(
                  'Choose the draw you want to check',
                  style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w600,
                    color: Colors.black,
                  ),
                ),
              ),
              Expanded(
                  child: ListView(
                controller: _scrollController,
                scrollDirection: Axis.horizontal,
                children: days,
              )),
            ],
          ),
        ),
        //分割线
        Container(
          height: 1,
          color: HexColor('#eeeeee'),
        ),

        GestureDetector(
          onTap: () {
            debugPrint('1st prize');
            _goToResultDetailPage(_prizes);
          },
          child: Container(
            color: Colors.white,
            padding: const EdgeInsets.only(top: 10, bottom: 1),
            // child: KalDrawnumbersview(data: numbersMap),
            child: Column(
              children: [
                KalDrawnumbersview(data: numbersMap),
                Container(
                  alignment: Alignment.topCenter,
                  // color: Colors.yellow,
                  height: 20,
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          'Full Details',
                          style: TextStyle(
                              color: HexColor('#666666'), fontSize: 10),
                        ),
                        Icon(Icons.arrow_right, color: HexColor('#666666'))
                      ]),
                ),
              ],
            ),
          ),
        )
      ],
    );
  }

  //
  Widget DateView(Map dateMap, int index) {
    var week = dateMap['weekDay'];
    var day = dateMap['day'];
    Color bgColor = index == _currentDayIndex
        ? KaL_Config.KaL_MainColor
        : HexColor('#eeeeee');
    Color titleColor = index == _currentDayIndex ? Colors.white : Colors.black;
    return GestureDetector(
      onTap: () {
        debugPrint('change day');
        _drawDateClick(index);
      },
      child: Container(
        width: 46,
        margin: const EdgeInsets.fromLTRB(5, 10, 5, 10),
        decoration: BoxDecoration(
            color: bgColor,
            borderRadius: const BorderRadius.all(Radius.circular(10))),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Padding(
              padding: const EdgeInsets.only(top: 3),
              child: Text(
                week,
                style: TextStyle(fontSize: 10, color: titleColor),
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(bottom: 0),
              child: Text(
                day,
                style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.w600,
                    color: titleColor),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget ListHeaderText() {
    return Container(
      padding: const EdgeInsets.only(left: 10),
      height: 50,
      alignment: Alignment.centerLeft,
      child: const Text(
        'My Tickets',
        style: TextStyle(
          fontSize: 13,
          fontWeight: FontWeight.w600,
          color: Colors.black,
        ),
      ),
    );
  }

  Widget ListFooterText() {
    return Container(
      padding: EdgeInsets.only(left: 10, right: 10),
      margin: const EdgeInsets.only(bottom: 15),
      alignment: Alignment.centerLeft,
      child: Text(
        'Please remember tickets displayed on this page are not valid entries into a lottery draw. Any winning amounts shown can only be claimed if you purchased a ticket with the same numbers for the same draw date.',
        style: TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.w400,
          color: HexColor('#999999'),
        ),
      ),
    );
  }
}
